<?php
namespace app\admin\controller;
use app\admin\controller\Base;
use app\admin\model\Admin;
use think\Request;
use think\Session;
use think\Url;

class  Login extends Base
{

    //加载登录视图
    public function index()
    {
        return view('login');
    }
    
    //用户登录
    public function tologin(Request $request){
        $login_info = $request->post();
        if(empty($login_info['username'])){
            $this->error("请输入用户名");
        }
        if(empty($login_info['password'])){
            $this->error("请输入密码");
        }
        //判断用户是否正确可以登录
        $res = Admin::where(array('username'=>$login_info['username'],"password"=>md5($login_info['password'])))->find();
        if($res){
            if($res['status'] == 2){
                $this->error("该用户正被调查！");
            }else {
                Admin::update(array("id" => $res['id'], "login_time" => time(), "login_ip" => $_SERVER['REMOTE_ADDR']));
                $res = Admin::where(array('username' => $login_info['username'], "password" => md5($login_info['password'])))->find();
                Session::set("user_info", $res);
                $this->asyn(); //登录时启动三天保护期 异步
                $this->success("登录成功", "Index/index");
            }
        }else{
            $this->error("用户名或密码错误");
        }
    }
    public function exits(){
        Session::delete("user_info");
        $this->redirect("Login/index");
    }


    // 实现异步调用 三天保护期执行程序
    public function asyn(){
        $url = $_SERVER['SERVER_NAME'];
        $fp = fsockopen($url, 80, $errno, $errstr, 30);
        if (!$fp) die('error fsockopen');
        stream_set_blocking($fp,0);
        $http = "GET /Admin/Login/aegisTime / HTTP/1.1\r\n";    
        $http .= "Host: $url\r\n";    
        $http .= "Connection: Close\r\n\r\n";
        fwrite($fp,$http);
        fclose($fp);

        return true;
    }
    //三天保护期执行程序
    public function aegisTime(){

        $aegis_time = 3600*24*3; //设置为三天
        $re = db('student')
            ->where(['sstatus'=>2])
            ->where('zxlast_time','<=', time()-$aegis_time)
            ->update(['sstatus'=>4,'drop_time'=>time()]);
            // $msg = date("Y-m-d H:i:s");
            // file_put_contents("log.txt", $msg."\n",FILE_APPEND);//记录日志
    }




    
}





